package com.bdy.translate.util;

import android.util.Log;

import com.bdy.translate.listener.ResultListener;
import com.sy.lib_secretkey.BaseCallBackListener;
import com.sy.lib_secretkey.SecretkeyUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BdyTranslateTool {
    private String appKey;
    private String secretKey;
    private ResultListener resultListener;
    private String access_token;
    //获取token的地址
    private String TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
    //文本翻译的地址
    private String TRANSLATE_URL = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1";

    public void initbdyKey(String defaultSecretKey, String keyName) {
        SecretkeyUtils.getSecretkey(defaultSecretKey, keyName, new BaseCallBackListener<String>() {
            @Override
            public void onSuccess(String s) {
                String[] res = SecretkeyUtils.formatKey(s);
                appKey = res[0];
                secretKey = res[1];
                getToken();
            }

            @Override
            public void onFailed(String s) {
                System.out.println("onFailed========" + s);
            }

            @Override
            public void onHandlerStart() {
                System.out.println("onHandlerStart========");
            }
        });
    }

    private void getToken() {
        //第一步，先获取token
        String url = TOKEN_URL + "?grant_type=client_credentials&client_id=" + appKey + "&client_secret=" + secretKey;
        requst(url, "", 1);
    }

    public void transLateToOtherLanguage(String from, String to, String q, ResultListener resultListener) {
        this.resultListener = resultListener;

        String content = "";
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("from", from);
            jsonObject1.put("to", to);
            jsonObject1.put("q", q);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        content = jsonObject1.toString();
        requst(TRANSLATE_URL + "?access_token=" + access_token, content, 2);
    }

    //发送请求的地址和数据
    private void requst(String url, String content, final int position) {
        System.out.println("uurl========" + url + "  content======" + content + "  access_token===" + access_token);
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        Request request = null;
        if (position == 1) {
            request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
        } else if (position == 2) {
            request = new Request.Builder()
                    .url(url)
                    .addHeader("access_token", access_token)
                    .post(RequestBody.create(mediaType, content))
                    .build();
        }

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("onResponse========" + e.getMessage());
                resultListener.Failed("翻译失败!");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                System.out.println("onResponse========" + res);
                if (position == 1) {
                    if (res == null || res.isEmpty()) {
                        resultListener.Failed("翻译失败!");
                        return;
                    }
                    try {
                        JSONObject jsonObject = new JSONObject(res);
                        access_token = jsonObject.getString("access_token");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else if (position == 2) {
                    System.out.println("res======" + res);
                    if (res == null || res.isEmpty()) {
                        resultListener.Failed("翻译失败!");
                        Log.e("TAG", "翻译失败");
                        return;
                    }
                    try {
                        Log.e("TAG", "翻译成功");
                        JSONObject jsonObject1 = new JSONObject(res);
                        if (jsonObject1.has("error_code")) {
                            if(jsonObject1.getInt("error_code") == 31201){
                                resultListener.Failed("字符数超过单次上限，翻译失败，请尝试减少字数");
                            }
                            Log.e("TAG", "翻译失败");
                            return;
                        }
                        Log.e("TAG", jsonObject1.toString());
                        JSONArray jsonArray = jsonObject1.getJSONObject("result").getJSONArray("trans_result");
                        if (jsonArray.length() > 0) {
                            StringBuilder result = new StringBuilder();
                            for(int i = 0;i < jsonArray.length();i++){
                                result.append(jsonArray.getJSONObject(i).getString("dst"));
                                result.append("\n\n");
                            }
                            resultListener.Success(result.toString());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
